﻿using nplJobsBLL.ProcessJob;
using nplJobsBLL.ProcessJobSeeker;
using nplJobsCommon.JobSeeker;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class JobSeeker_SavedJobs : System.Web.UI.Page
{
    #region Variables and Properties
    public Int64 AppliedJobID { get; set; }
    Image sortImage = new Image();
    Image sortSecondImage = new Image();
    Image sortThirdImage = new Image();

    public int CurrentSortDirection
    {
        get
        {
            if (Session["SortDireaction"] == null)
                return 0;
            else
                return int.Parse(Session["SortDireaction"].ToString());
        }
        set
        {
            Session["SortDireaction"] = value;
        }
    }
    #endregion

    #region LoadSavedJobs
    /// <summary>
    /// Load saved jobs
    /// </summary>
    private void LoadSavedJobs()
    {
        List<SavedJobToDisplay> savedJobs = new List<SavedJobToDisplay>();
        this.SavedJobID = -1;
        savedJobs = LoadSavedJobToDisplay();
        if (savedJobs != null)
        {
            Session["SavedJobs"] = savedJobs;
            //BindJobList(appliedJobs);
            //int numberPerPage = ConfigurationManager.AppSettings["PagingNumberPerPage"] != null ? int.Parse(ConfigurationManager.AppSettings["PagingNumberPerPage"].ToString()) : 0;
            this.GetSavedJobsPageWise(1);
        }
    }
    #endregion

    #region LoadSavedJobToDisplay
    /// <summary>
    /// Load saved job to show in the grid view
    /// </summary>
    /// <returns></returns>
    private List<SavedJobToDisplay> LoadSavedJobToDisplay()
    {
        ProcessSavedJobToDisplay savedJobToDisplay = new ProcessSavedJobToDisplay();
        MembershipUser userInfo = System.Web.Security.Membership.GetUser(HttpContext.Current.User.Identity.Name);
        //System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.GetUser();

        if (userInfo != null)
        {
            Guid jobseekerID = (Guid)userInfo.ProviderUserKey;
            savedJobToDisplay.JobseekerID = jobseekerID;
            savedJobToDisplay.SavedJobID = this.SavedJobID;
            savedJobToDisplay.invoke();
        }
        return savedJobToDisplay.SavedJobToDisplay;
    }
    #endregion

    #region BindJobList
    /// <summary>
    /// Bind job list to the griv view
    /// </summary>
    /// <param name="appliedJobs"></param>
    private void BindJobList(List<SavedJobToDisplay> savedJobs)
    {
        gvJobList.DataSource = savedJobs;
        gvJobList.DataBind();
        sortImage.ImageUrl = "../Images/view_sort_ascending.png";
        //sortSecondImage.ImageUrl = "../Images/view_sort_ascending.png";
        //sortThirdImage.ImageUrl = "../Images/view_sort_ascending.png";

        if (savedJobs.Count > 0)
            gvJobList.HeaderRow.Cells[1].Controls.Add(sortImage);
        //gvJobList.HeaderRow.Cells[3].Controls.Add(sortSecondImage);
        //gvJobList.HeaderRow.Cells[4].Controls.Add(sortThirdImage);

        if (savedJobs.Count == 0)
        {
            rptPager.Visible = false;
            ddlPageSize.Visible = false;
        }
        else
        {
            ddlPageSize.Visible = true;
            rptPager.Visible = true;
        }
    }
    #endregion

    #region GetSavedJobsPageWise
    /// <summary>
    /// Get customers page wise
    /// </summary>
    /// <param name="pageIndex"></param>
    private void GetSavedJobsPageWise(int pageIndex)
    {
        MembershipUser userInfo = System.Web.Security.Membership.GetUser(HttpContext.Current.User.Identity.Name);
        System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.GetUser();
        Guid jobseekerID = (Guid)userInfo.ProviderUserKey;

        ProcessSavedJobsPageWise savedJobs = new ProcessSavedJobsPageWise();
        savedJobs.PageIndex = pageIndex == -1 ? 1 : pageIndex;
        if (pageIndex == -1)
        {
            int maxValue = ddlPageSize.Items.Cast<ListItem>().Select(item => int.Parse(item.Value)).Max();
            savedJobs.PageSize = maxValue;
            ddlPageSize.SelectedIndex = ddlPageSize.Items.IndexOf(ddlPageSize.Items.FindByText(maxValue.ToString()));
        }
        else
        {
            savedJobs.PageSize = int.Parse(ddlPageSize.SelectedValue);
        }
        savedJobs.JobseekerID = jobseekerID;
        savedJobs.invoke();
        List<SavedJobToDisplay> savedJobPageWise = savedJobs.SavedJobToDisplay;
        Session["SavedJobs"] = savedJobPageWise;
        BindJobList(savedJobPageWise);


        int recordCount = savedJobs.RecordCount;
        this.PopulatePager(recordCount, pageIndex);
    }
    #endregion

    #region PopulatePager
    /// <summary>
    /// Populate pager to paging in the griv view
    /// </summary>
    /// <param name="recordCount"></param>
    /// <param name="currentPage"></param>
    private void PopulatePager(int recordCount, int currentPage)
    {
        double dblPageCount = (double)((decimal)recordCount / decimal.Parse(ddlPageSize.SelectedValue));
        int pageCount = (int)Math.Ceiling(dblPageCount);
        List<ListItem> pages = new List<ListItem>();
        if (pageCount > 0)
        {
            pages.Add(new ListItem("First", "1", currentPage > 1));
            for (int i = 1; i <= pageCount; i++)
            {
                pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
            }
            if (pageCount == 1)
                pages.Add(new ListItem("Last", pageCount.ToString(), false));
            else
                pages.Add(new ListItem("Last", pageCount.ToString(), currentPage < pageCount));
        }
        rptPager.DataSource = pages;
        rptPager.DataBind();
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Context.User.Identity.IsAuthenticated)
            Response.Redirect("~/Default.aspx");

        if (!IsPostBack)
        {
            Page.Title = "npljobs.com || Saved jobs";

                Label lblTitle = Page.Master.FindControl("lblTitle") != null ? (Label)Page.Master.FindControl("lblTitle") : new Label();
                lblTitle.Text = "Saved job(s)";



            //txtSearch.Attributes.Add("onblur", "WaterMark(this, event);");
            //txtSearch.Attributes.Add("onfocus", "WaterMark(this, event);");

            LoadSavedJobs();
        }
    }
    protected void Page_Changed(object sender, EventArgs e)
    {
        int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
        this.GetSavedJobsPageWise(pageIndex);
    }
    protected void ddlPageSize_Changed(object sender, EventArgs e)
    {
        //int numberPerPage = ConfigurationManager.AppSettings["PagingNumberPerPage"] != null ? int.Parse(ConfigurationManager.AppSettings["PagingNumberPerPage"].ToString()) : 0;
        this.GetSavedJobsPageWise(1);
    }
    protected void gvJobList_Sorting(object sender, GridViewSortEventArgs e)
    {
        List<SavedJobToDisplay> appliedJobs = (List<SavedJobToDisplay>)Session["SavedJobs"];
        int currentSortDirection = CurrentSortDirection;
        if (appliedJobs != null)
        {
            //int numberPerPage = ConfigurationManager.AppSettings["PagingNumberPerPage"] != null ? int.Parse(ConfigurationManager.AppSettings["PagingNumberPerPage"].ToString()) : 0;
            this.GetSavedJobsPageWise(1);

            var param = Expression.Parameter(typeof(SavedJobToDisplay), e.SortExpression);
            var sortExpression = Expression.Lambda<Func<SavedJobToDisplay, object>>(Expression.Convert(Expression.Property(param, e.SortExpression), typeof(object)), param);

            //Set the list ordered ascending as datasource
            if (currentSortDirection == (int)SortDirection.Ascending)
            {
                gvJobList.DataSource = appliedJobs.AsQueryable<SavedJobToDisplay>().OrderBy(sortExpression).ToList();
            }
            //Set the list ordered descending as datasource
            else
            {
                gvJobList.DataSource = appliedJobs.AsQueryable<SavedJobToDisplay>().OrderByDescending(sortExpression).ToList();
            }
            if (currentSortDirection == (int)SortDirection.Ascending)
            {
                CurrentSortDirection = (int)SortDirection.Descending;
                sortImage.ImageUrl = "../Images/view_sort_ascending.png";
                //sortSecondImage.ImageUrl = "../Images/view_sort_ascending.png";
                //sortThirdImage.ImageUrl = "../Images/view_sort_ascending.png";
            }
            else
            {
                CurrentSortDirection = (int)SortDirection.Ascending;
                sortImage.ImageUrl = "../Images/view_sort_descending.png";
                //sortSecondImage.ImageUrl = "../Images/view_sort_descending.png";
                //sortThirdImage.ImageUrl = "../Images/view_sort_descending.png";
            }

            gvJobList.DataBind();
            int columnIndex = 0;
            foreach (DataControlFieldHeaderCell headerCell in gvJobList.HeaderRow.Cells)
            {
                if (headerCell.ContainingField.SortExpression == e.SortExpression)
                {
                    columnIndex = gvJobList.HeaderRow.Cells.GetCellIndex(headerCell);
                }
            }

            gvJobList.HeaderRow.Cells[1].Controls.Add(sortImage);
            //gvJobList.HeaderRow.Cells[3].Controls.Add(sortSecondImage);
            //gvJobList.HeaderRow.Cells[4].Controls.Add(sortThirdImage);
        }
    }
    protected void gvJobList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int applicationDateline = ((SavedJobToDisplay)e.Row.DataItem).ApplicationDateline;
            if (applicationDateline <= 0)
            {
                Label lblApplicationDateline = (Label)e.Row.FindControl("lblApplicationDateline");
                lblApplicationDateline.ForeColor = System.Drawing.Color.Red;
                lblApplicationDateline.Text = "Expired";
                //e.Row.Cells[4].Text = "Expired";
            }
            else
            {
                Label lblApplicationDateline = (Label)e.Row.FindControl("lblApplicationDateline");
                lblApplicationDateline.Text = applicationDateline.ToString() + " days";
                // int dl = ((AppliedJobToDisplay)e.Row.DataItem).ApplicationDateline;
                // e.Row.Cells[4].Text = dl.ToString() + " days";
            }
        }
    }
    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        if (txtSearch.Text == "Write text and press enter")
            return;
        else
        {
            if (txtSearch.Text != string.Empty)
            {
                MembershipUser userInfo = System.Web.Security.Membership.GetUser(HttpContext.Current.User.Identity.Name);
                System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.GetUser();
                Guid jobSeekerID = (Guid)userInfo.ProviderUserKey;

                int dealine = -1;
                bool isParsed = int.TryParse(txtSearch.Text.Trim(), out dealine);

                ProcessSelectSavedJobByParam selectSavedJob = new ProcessSelectSavedJobByParam();
                selectSavedJob.JobTitle = ddlSearchBy.SelectedItem.Text.Equals("Job Title") ? txtSearch.Text.Trim() : string.Empty;
                selectSavedJob.Location = ddlSearchBy.SelectedItem.Text.Equals("Location") ? txtSearch.Text.Trim() : string.Empty;
                selectSavedJob.Deadline = ddlSearchBy.SelectedItem.Text.Equals("Deadline") ? dealine : 0;
                selectSavedJob.JobSeekerId = jobSeekerID;

                List<SavedJobToDisplay> savedJobs = new List<SavedJobToDisplay>();

                if (ddlSearchBy.SelectedItem.Text.Equals("Deadline") && selectSavedJob.Deadline <= 0)
                {
                    savedJobs = new List<SavedJobToDisplay>();
                }
                else
                {
                    selectSavedJob.invoke();
                }

                if (selectSavedJob.SavedJobToDisplay != null && selectSavedJob.SavedJobToDisplay.Count > 0)
                {
                    savedJobs = selectSavedJob.SavedJobToDisplay;
                    BindJobList(savedJobs);
                }
                else
                {
                    BindJobList(savedJobs);
                }
            }
        }

        if (ddlSearchBy.Text == "Deadline")
        {
            lblMsg.InnerText = "i.e. 10 (in days)";
        }
        else
        {
            lblMsg.InnerText = "";
        }
    }

    protected void btnYes_Click(object sender, ImageClickEventArgs e)
    {
        lblSaveMsg.Text = string.Empty;

        DataTable dtSavedJobIds = new DataTable();
        dtSavedJobIds.Columns.Add("SavedJobID", typeof(int));
        dtSavedJobIds.NewRow();

        List<string> ids = new List<string>();
        string id = string.Empty;

        for (int i = 0; i < gvJobList.Rows.Count; i++)
        {
            CheckBox cb = (CheckBox)gvJobList.Rows[i].Cells[4].FindControl("chkDelete");
            if (cb != null)
            {
                if (cb.Checked)
                {
                    id = gvJobList.Rows[i].Cells[0].Text;
                    dtSavedJobIds.Rows.Add(id);
                }
            }
        }

        bool isDeleted = false;

        ProcessDeleteJobSeekerSavedJobs deleteSavedJobs = new ProcessDeleteJobSeekerSavedJobs();
        deleteSavedJobs.SavedJobToDisplay = dtSavedJobIds;
        deleteSavedJobs.invoke();
        isDeleted = deleteSavedJobs.IsDeleted;
        if (isDeleted)
        {
            lblSaveMsg.Text = "Selected jobs are deleted";
            LoadSavedJobs();
            lblSaveMsg.ForeColor = System.Drawing.Color.Green;
            ScriptManager.RegisterStartupScript(this, GetType(), "ClearSaveMsg", "ClearSaveMsg();", true);

        }
        else
        {
            lblSaveMsg.ForeColor = System.Drawing.Color.Red;
            lblSaveMsg.Text = "Failed to delete selected jobs";
            ScriptManager.RegisterStartupScript(this, GetType(), "ClearSaveMsg", "ClearSaveMsg();", true);
        }
    }
    public void btnDeleteSeledRows_Click(object sender, EventArgs e)
    {
        lblSaveMsg.Text = string.Empty;
        lblText.InnerText = "Are you sure to delete job(s)?";
        ModalPopupExtender1.Show();
    }
    protected void btnShowAll_Click(object sender, EventArgs e)
    {
        lblSaveMsg.Text = string.Empty;
        RefreshSavedJobs(-1);
    }

    //protected void ddlSearchBy_SelectedIndexChanged(object sender, EventArgs e)
    //{
    //    //if (ddlSearchBy.Text == "All")
    //   // {
    //    //    RefreshSavedJobs();
    //    //}
    //    //else
    //    //if (ddlSearchBy.Text == "Deadline")
    //    //{
    //    //    //RefreshSavedJobs();
    //    //    lblMsg.InnerText = "i.e. Specified number is less than or equal to the dealine";
    //    //}
    //    //else
    //    //{
    //    //   // RefreshSavedJobs();
    //    //    lblMsg.InnerText = "";
    //    //}
    //}
    #endregion

    #region RefreshAppliedJobs
    /// <summary>
    /// Refresh applied jobs
    /// </summary>
    private void RefreshSavedJobs(int value)
    {
        List<SavedJobToDisplay> savedJobs = new List<SavedJobToDisplay>();
        this.SavedJobID = -1;
        savedJobs = LoadSavedJobToDisplay();
        if (savedJobs != null)
        {
            Session["SavedJobs"] = savedJobs;
            //BindJobList(appliedJobs);
            //  int numberPerPage = ConfigurationManager.AppSettings["PagingNumberPerPage"] != null ? int.Parse(ConfigurationManager.AppSettings["PagingNumberPerPage"].ToString()) : 0;
            this.GetSavedJobsPageWise(value);
        }
        else
        {
            BindJobList(savedJobs);
        }
    }
    #endregion

    public int SavedJobID { get; set; }
}